package com.bxd.baodan.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.BaodanManagerActivity;
import com.bxd.baodan.activity.BaseActivity;
import com.bxd.baodan.activity.FamilyDesignActivity;
import com.bxd.baodan.activity.FamilyManagerActivity;
import com.bxd.baodan.activity.FastSelectBaoxianActivity;
import com.bxd.baodan.activity.GanHuoActivity;
import com.bxd.baodan.activity.LipeiActivity2;
import com.bxd.baodan.activity.MainActivity;
import com.bxd.baodan.activity.PlanerActivity;
import com.bxd.baodan.activity.SchemeAllActivity;
import com.bxd.baodan.activity.SearchAllActivity;
import com.bxd.baodan.activity.WebViewPager;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.SchemeAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.BannerBean;
import com.bxd.baodan.item.BannerBean.BannerBean_;
import com.bxd.baodan.item.GanHuoBean;
import com.bxd.baodan.item.ProductItem;
import com.bxd.baodan.item.ProductSelectBaseBean;
import com.bxd.baodan.item.RecomendBean;
import com.bxd.baodan.item.ReportStatus;
import com.bxd.baodan.item.SchemeBean;
import com.bxd.baodan.item.SchemeBean.DataBean.SchemeBean_;
import com.bxd.baodan.item.ToutiaoItem;
import com.bxd.baodan.item.ToutiaoItem.DataItem.ToutiaoBean;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.GsonUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SpKey;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.util.Utils;
import com.bxd.baodan.util.VersionUtil;
import com.bxd.baodan.widget.IosDialog;
import com.bxd.baodan.widget.MarqueeView;
import com.bxd.baodan.widget.MyListView;
import com.bxd.baodan.widget.NetworkImageHolderView;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


public class MainHomeFragment extends BaseFragment implements View.OnClickListener, OnItemClickListener {

    List<View> touTiaoViews = new ArrayList<>();
    private RecyclerView schemeLv;
    private MyListView topicLv;
    private BroadcastReceiver receiveBroadCast;
    private View view;


    List<BannerBean_> bannerList = new ArrayList<>();
    List<SchemeBean_> schemeList = new ArrayList<>();
    List<ToutiaoBean> toutiaoList = new ArrayList<>();
    List<GanHuoBean> hotTopicList = new ArrayList<>();
    List<ProductItem> recommendList1 = new ArrayList<>();
    List<ProductItem> recommendList2 = new ArrayList<>();
    private SchemeAdapter schemeAdapter;


    CommonAdapter hotTopicAdapter;


    private ScrollView scrollView;
    private LinearLayout homeChangeColor;
    private ImageView homeSearch;
    private TextView homeToReport;
    private LinearLayout homeNoScoreLy;
    private LinearLayout homeHaveScoreLy;
    private TextView homeScoreTv;
    private TextView homeStatusTv;
    private TextView homeGoUpTv;
    private TextView homeGoTestTv;
    private MarqueeView homeTopNews;
    private TextView baodanGuanli;
    private TextView zixunGuwen;
    private TextView homeWendaTv;
    private TextView homeLipeiTv;
    private ImageView homeXuanBaoxianIv;
    private ImageView homeLingFuliIv;
    private ConvenientBanner homeBanner;
    private TextView homeSchemeMore;
    private RecyclerView homeSchemeLv;
    private TextView homeGanhuoMore;
    private MyListView homeGanhuoLv;
    private RelativeLayout title_bar;
    TextView my_family;
    RecyclerView tuijian_lv_1;
    LinearLayout tj_ly;
    BaseQuickAdapter<ProductItem, BaseViewHolder> tjAdapter1;


    private ReportStatus reportStatus;
    private TextView tuijian_group_name_2, tuijian_group_name_1, tuijian_group_dsc_1;


    public static MainHomeFragment getInstance() {
        return new MainHomeFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home_page_1, container, false);
        }
        ViewGroup viewGroup = (ViewGroup) view.getParent();
        if (viewGroup != null) {
            viewGroup.removeAllViewsInLayout();
        }
        initView();
        return view;

    }


    public void initView() {

        title_bar = view.findViewById(R.id.title_bar);

        title_bar.setPadding(title_bar.getPaddingLeft(), title_bar.getPaddingTop() + getStatusBarHeight(),
                title_bar.getPaddingRight(), title_bar.getPaddingBottom());

        zixunGuwen = view.findViewById(R.id.zixun_guwen);
        baodanGuanli = view.findViewById(R.id.baodan_guanli);
        my_family = view.findViewById(R.id.my_family);
        my_family.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginStatus()) {
                    openActivity(FamilyManagerActivity.class);
                }
            }
        });

        schemeLv = (RecyclerView) view.findViewById(R.id.home_scheme_lv);
        topicLv = (MyListView) view.findViewById(R.id.home_ganhuo_lv);


        scrollView = (ScrollView) view.findViewById(R.id.scrollView);

        scrollView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        homeChangeColor = (LinearLayout) view.findViewById(R.id.home_change_color);
        // TODO: 18/1/19 设置状态栏高度
        // TODO: 2018/1/11 换色
        //  homeChangeColor.setBackground(getResources().getDrawable(0));


        homeSearch = (ImageView) view.findViewById(R.id.home_search);
        homeSearch.setOnClickListener(this);
        homeToReport = (TextView) view.findViewById(R.id.home_to_report);
        homeToReport.setOnClickListener(this);
        homeTopNews = (MarqueeView) view.findViewById(R.id.home_top_news);


        homeNoScoreLy = (LinearLayout) view.findViewById(R.id.home_no_score_ly);
        homeHaveScoreLy = (LinearLayout) view.findViewById(R.id.home_have_score_ly);


        homeScoreTv = (TextView) view.findViewById(R.id.home_score_tv);

        homeStatusTv = (TextView) view.findViewById(R.id.home_status_tv);
        homeGoUpTv = (TextView) view.findViewById(R.id.home_go_up_tv);
        homeGoTestTv = (TextView) view.findViewById(R.id.home_go_test_tv);
        homeBanner = (ConvenientBanner) view.findViewById(R.id.home_banner);
        homeSchemeMore = (TextView) view.findViewById(R.id.home_scheme_more);
        homeGanhuoMore = (TextView) view.findViewById(R.id.home_ganhuo_more);

        homeSchemeLv = (RecyclerView) view.findViewById(R.id.home_scheme_lv);
        homeGanhuoLv = (MyListView) view.findViewById(R.id.home_ganhuo_lv);

        baodanGuanli = (TextView) view.findViewById(R.id.baodan_guanli);
        zixunGuwen = (TextView) view.findViewById(R.id.zixun_guwen);
        homeWendaTv = (TextView) view.findViewById(R.id.home_wenda_tv);


        homeLipeiTv = (TextView) view.findViewById(R.id.home_lipei_tv);
        homeXuanBaoxianIv = (ImageView) view.findViewById(R.id.home_xuan_baoxian_iv);
        homeLingFuliIv = (ImageView) view.findViewById(R.id.home_ling_fuli_iv);


        tuijian_group_name_1 = (TextView) view.findViewById(R.id.tuijian_group_name_1);
        tuijian_group_dsc_1 = (TextView) view.findViewById(R.id.tuijian_group_dsc_1);
        tuijian_group_name_2 = (TextView) view.findViewById(R.id.tuijian_group_name_2);
        tuijian_lv_1 = (RecyclerView) view.findViewById(R.id.tuijian_lv_1);

        tj_ly = view.findViewById(R.id.tj_ly);


        homeLipeiTv.setOnClickListener(this);
        homeXuanBaoxianIv.setOnClickListener(this);
        homeLingFuliIv.setOnClickListener(this);
        homeWendaTv.setOnClickListener(this);
        zixunGuwen.setOnClickListener(this);
        baodanGuanli.setOnClickListener(this);
        homeSchemeMore.setOnClickListener(this);
        homeGanhuoMore.setOnClickListener(this);
        homeGoUpTv.setOnClickListener(this);
        homeGoTestTv.setOnClickListener(this);
        homeStatusTv.setOnClickListener(this);


        // FIXME: 17/7/14 解决listView跳动问题,将焦点设置到顶部view就行了
        homeSearch.setFocusable(true);
        homeSearch.setFocusableInTouchMode(true);
        homeSearch.requestFocus();
        initBroadCastReceiver();

        setAdapter();


        // TODO: 2017/8/28 banner


        getBannerData();
        //todo 头条
        getTopNews();
        //todo  精选方案
        getSchemeData();
        // TODO: 2017/8/28  干货
        getGanHuoData();

        getRecommendData();

        onHiddenChanged(false);

        showReportStatus();

    }

    private void setAdapter() {
        setBanner();
        setScheme();
        setGanHuo();
        setRecommend();
    }

    private void setRecommend() {
        tjAdapter1 = new BaseQuickAdapter<ProductItem, BaseViewHolder>(R.layout.home_recommend_item_1, recommendList1) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, final ProductItem productItem) {
                GlideUtil.loadImage(getActivity(), productItem.p_img, (ImageView) baseViewHolder.getView(R.id.p_image));
                baseViewHolder.setText(R.id.p_name, productItem.p_name);
                baseViewHolder.getView(R.id.p_image).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String url = productItem.p_url;
                        openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url});
                    }
                });

            }
        };

        tuijian_lv_1.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        tuijian_lv_1.setAdapter(tjAdapter1);
    }

    private void showReportStatus() {
        if (LoginInfo.getInstance().isLogin()) {
            getReportData();
        } else {
            setNoScoreBg();
        }
    }

    private void getReportData() {

        if (LoginInfo.getInstance().isLogin()) {
            String cache = SpUtil.getInstance().getString(SpKey.HOME_REPORTSTATUS);
            if (!StringUtil.isEmpty(cache)) {
                reportStatus = (ReportStatus) GsonUtil.fromJson(cache, ReportStatus.class);
            }
            if (reportStatus == null || reportStatus.score == null) {
                setNoScoreBg();
            } else {
                setScoredBg(reportStatus.score, reportStatus.score_level);
            }
        } else {
            setNoScoreBg();
        }

        NetUtil netUtil = new NetUtil(getActivity(), JsonApi.DESIGN_DESIGNSTATUS);
        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {

                reportStatus = (ReportStatus) GsonUtil.fromJson(data, ReportStatus.class);
                if (reportStatus.score == null) {
                    setNoScoreBg();
                } else {
                    setScoredBg(reportStatus.score, reportStatus.score_level);
                }
                SpUtil.getInstance().savaString(SpKey.HOME_REPORTSTATUS, data);
            }
        });

    }

    private void setScoredBg(String score, String scoreLevel) {
        String str = "";

        int bg = R.drawable.home_bg_best;
        String color = "#24c36d";
        switch (scoreLevel) {
            //较差
            case "0":
                bg = R.drawable.home_bg_bad;
                color = "#fa7b5c";
                str = "较低";
                break;
            //一般
            case "1":
                bg = R.drawable.home_bg_normal;
                color = "#fe9e24";
                str = "一般";
                break;
            //良好
            case "2":
                bg = R.drawable.home_bg_better;
                color = "#0eb8c8";
                str = "较高";
                break;
            //优秀
            case "3":
                bg = R.drawable.home_bg_best;
                color = "#24c36d";
                str = "爆表";
                break;
        }
        title_bar.setBackgroundColor(Color.parseColor(color));
        homeChangeColor.setBackground(getResources().getDrawable(bg));
        homeNoScoreLy.setVisibility(View.GONE);
        homeHaveScoreLy.setVisibility(View.VISIBLE);
        homeGoTestTv.setVisibility(View.GONE);
        homeGoUpTv.setVisibility(View.VISIBLE);
        homeGoUpTv.setTextColor(Color.parseColor(color));
        homeScoreTv.setText(score);
        homeStatusTv.setText(str);
        homeToReport.setVisibility(View.VISIBLE);


    }

    private void setNoScoreBg() {

        title_bar.setBackgroundColor(Color.parseColor("#24c36d"));
        homeChangeColor.setBackground(getResources().getDrawable(R.drawable.home_bg_best));
        homeNoScoreLy.setVisibility(View.VISIBLE);
        homeHaveScoreLy.setVisibility(View.GONE);
        homeGoTestTv.setVisibility(View.VISIBLE);
        homeGoUpTv.setVisibility(View.GONE);
        homeToReport.setVisibility(View.GONE);
    }


    private void getRecommendData() {

        String cache = SpUtil.getInstance().getString(SpKey.HOME_RECOMMEND);
        if (!StringUtil.isEmpty(cache)) {
            String array = JSONUtil.getArrayData("list", cache);
            List<RecomendBean> list = new Gson().fromJson(array, new TypeToken<List<RecomendBean>>() {
            }.getType());

            if (list != null && list.size() > 0) {
                SpUtil.getInstance().savaString(SpKey.HOME_RECOMMEND, cache);
                showRecommendUI(list);
            }

        }

        NetUtil netUtil = new NetUtil(getActivity(), JsonApi.PRODUCT_AIRECOMMEND);
        netUtil.postRequest("", new NetUtil.DataListener() {

            @Override
            public void onComplete(String data) {

                String array = JSONUtil.getArrayData("list", data);
                List<RecomendBean> list = new Gson().fromJson(array, new TypeToken<List<RecomendBean>>() {
                }.getType());

                if (list != null && list.size() > 0) {
                    SpUtil.getInstance().savaString(SpKey.HOME_RECOMMEND, data);
                    showRecommendUI(list);
                }
            }
        });

    }


    private void showRecommendUI(List<RecomendBean> list) {
        tuijian_group_name_1.setText(list.get(0).group_name);
        tuijian_group_dsc_1.setText(list.get(0).group_desc);
        tuijian_group_name_2.setText(list.get(1).group_name);

        recommendList1.clear();
        recommendList1.addAll(list.get(0).product_list);
        recommendList2.clear();
        recommendList2.addAll(list.get(1).product_list);
        tjAdapter1.notifyDataSetChanged();

        for (int i = 0; i < 2; i++) {
            View view;
            if (i == 0) {
                view = tj_ly.getChildAt(0);
            } else {
               view = tj_ly.getChildAt(2);
            }
            ImageView iv = view.findViewById(R.id.tuijian_iv);
            TextView tv_name = view.findViewById(R.id.p_name);
            TextView tv_dec = view.findViewById(R.id.p_dec);


            iv.setImageResource(i == 0 ? R.drawable.home_tuijian_left : R.drawable.home_tuijian_right);
            tv_dec.setText(recommendList2.get(i).p_desc);
            tv_name.setText(recommendList2.get(i).p_name);

            final int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String url = recommendList2.get(finalI).p_url;
                    openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url});
                }
            });
        }
    }


    private void setScheme() {
        schemeAdapter = new SchemeAdapter(schemeList, getActivity());
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        schemeLv.setLayoutManager(linearLayoutManager);
        schemeLv.setAdapter(schemeAdapter);

    }

    private void getSchemeData() {
        String cacheScheme = SpUtil.getInstance().getString("sp_home_scheme");
        if (!StringUtil.isEmpty(cacheScheme)) {
            SchemeBean bean = new Gson().fromJson(cacheScheme, SchemeBean.class);
            List<SchemeBean_> bean_ = bean.data.list;
            schemeList.clear();
            schemeList.addAll(bean_);
            schemeAdapter.notifyDataSetChanged();
        }

        // TODO: 2017/8/28 精选方案
        NetUtil netUtil = new NetUtil(getActivity(), JsonApi.SCHEME_LIST);
        netUtil.setParams("type", "1");

        netUtil.postRequest("加载中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                SchemeBean bean = new Gson().fromJson(result, SchemeBean.class);
                List<SchemeBean_> bean_ = bean.data.list;
                if (bean_ != null && bean_.size() > 1) {
                    SpUtil.getInstance().savaString("sp_home_scheme", result);
                }
                schemeList.clear();
                schemeList.addAll(bean_);
                schemeAdapter.notifyDataSetChanged();
            }
        });
    }


    private void setBanner() {
        // TODO: 2017/8/28 banner设置
        homeBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, bannerList)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                //                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)


                .setOnItemClickListener(this).startTurning(4000);

    }

    private void getBannerData() {

        //banner的缓存数据
//        String bannerCache = SpUtil.getInstance().getString("new_banner");
//        if (bannerCache != null && !bannerCache.isEmpty()) {
//            BannerBean bannerBean = new Gson().fromJson(bannerCache, BannerBean.class);
//            List<BannerBean_> list = bannerBean.data;
//            if (list != null && list.size() > 0) {
//                bannerList.clear();
//                bannerList.addAll(list);
//                homeBanner.notifyDataSetChanged();
//            }
//        }


        //banner数据
        NetUtil adNet = new NetUtil(this.getActivity(), JsonApi.GET_ADHOME);
        adNet.setParams("app", 2);
        adNet.setParams("channel", Utils.getAppMetaData(App.getContext(), "UMENG_CHANNEL"));
        adNet.setParams("appVer", VersionUtil.getVersionName(this.getActivity()));
        adNet.setParams("position", "wenwen_main_banner");

        adNet.postRequest("", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {

                BannerBean bannerBean = new Gson().fromJson(result, BannerBean.class);
                List<BannerBean_> list = bannerBean.data;
                if (list != null && list.size() > 0) {
                    SpUtil.getInstance().savaString("new_banner", result);

                    bannerList.clear();
                    bannerList.addAll(list);
                    homeBanner.notifyDataSetChanged();
                }

            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.ECLAIR)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.home_status_tv:

                new IosDialog(getActivity()).builder().setCancelable(true)
                        .setTitle("保险岛幸福指数")
                        .setMsg("是你完成家庭保障测评后,基于各维度信息,通过人工智能、精算专家智慧、海量大数据等计算分析,客观呈现的个人家庭幸福指数综合评分,分数越高,表明保险岛幸福指数越高")
                        .setNegativeButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            }
                        }).show();

                break;

            case R.id.home_go_test_tv:
                if (loginStatus()) {
                    openActivity(FamilyDesignActivity.class);
                }

                break;


            //方案更多
            case R.id.home_scheme_more:
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_fagd");
                openActivity(SchemeAllActivity.class);

                break;


            //干货更多
            case R.id.home_ganhuo_more:
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_ghgd");
                openActivity(GanHuoActivity.class);
                break;


            //咨询顾问
            case R.id.zixun_guwen:
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_zxzx");
                openActivity(PlanerActivity.class);


                break;

            //保单管理
            case R.id.baodan_guanli:
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_bdgl");
                openActivity(BaodanManagerActivity.class);

                break;

            //搜索
            case R.id.home_search:
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_ss");
                openActivity(SearchAllActivity.class);
                break;


            //方案报告
            case R.id.home_to_report:
                if (loginStatus()) {
                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_fabg");
                    String uid = LoginInfo.getInstance().getUid();
                    String url = Constant.root_url + "html/design/detail?uid=" + uid;

                    openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url});

                }

                break;
//去提升
            case R.id.home_go_up_tv:
                if (loginStatus()) {

                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_qts");
                    String uid = LoginInfo.getInstance().getUid();
                    String url = Constant.root_url + "html/design/detail?uid=" + uid + "#jt";
                    openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url});
                }

                break;


            //跳到问答
            case R.id.home_wenda_tv:
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_bxwd");
                ((MainActivity) getActivity()).setTabSelection(1);
                break;
            //理赔援助
            case R.id.home_lipei_tv:

                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_lpyz");
                openActivity(LipeiActivity2.class);
                break;
            //个人测评
            case R.id.home_xuan_baoxian_iv:
                if (loginStatus()) {
                    openActivity(FastSelectBaoxianActivity.class);
                }
                break;
            //领福利
            case R.id.home_ling_fuli_iv:
                // TODO: 2018/1/11
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_kllfl");
                if (((MainActivity) getActivity()).fragment_3 == null) {

                    getSortData();


                } else {
                    ((MainActivity) getActivity()).fragment_3.toFree();
                    ((MainActivity) getActivity()).setTabSelection(2);
                }
                break;

            default:
                break;
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //停止翻页
            homeBanner.stopTurning();
            homeTopNews.stopFlipping();
        } else {
            //开始自动翻页
            homeBanner.startTurning(4000);
            homeTopNews.startFlipping();


            if (bannerList.size() == 0) {
                getBannerData();
            }

            if (schemeList.size() == 0) {
                getSchemeData();
            }
            if (toutiaoList.size() == 0) {
                refreshTopNews();
            }
            if (hotTopicList.size() == 0) {
                getGanHuoData();
            }

        }
    }


    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class<?> clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }


    // TODO: 17/9/19 轮播
    @Override
    public void onItemClick(int position) {
        LogUtil.e("轮播图点击-->");
        MobclickAgent.onEvent(App.getContext(),
                "UM_v6_0_0_SY_lbt", bannerList.get(position).title);
        if (bannerList.get(position).type == 1) {
            Uri content_url = Uri.parse(bannerList.get(position).data.gotoUrl);
            if (content_url != null && !content_url.toString().trim().equals("")) {
                Intent intent = new Intent(getActivity(), WebViewPager.class);
                String url = content_url.toString();

                intent.putExtra("startUrl", url);
                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().overridePendingTransition(R.anim.slide_in_right,
                            R.anim.slide_out_left);
                }
            }

        } else {
            //跳转到page
            gotoActivity(bannerList.get(position).data.gotoPage.android);
        }


    }

    //轮播跳转具体界面用
    public void gotoActivity(String actname) {
        String actPrex = "com.bxd.baodan.activity.";
        Class<?> ass = null;
        try {
            ass = Class.forName(actPrex + actname);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (ass != null) {
            Intent intent = new Intent(getActivity(), ass);
            startActivity(intent);
        }
    }


    public void setGanHuo() {

        // TODO: 2017/8/28 干货


        hotTopicAdapter = new CommonAdapter<GanHuoBean>(this.getActivity(),
                hotTopicList,
                R.layout.gan_huo_item) {

            @Override
            public void convert(final ViewHolder holder, final GanHuoBean item) {
                GlideUtil.loadImage(getActivity(), item.image, ((ImageView) holder.getView(R.id.image)));

                holder.setText(R.id.title, item.title);
                holder.setText(R.id.read, item.viewCount + "阅读");
                holder.setText(R.id.tag, item.category.name);
                holder.getView(R.id.main).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_ghgd_wzxq");
                        openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{item.url});
                    }
                });


            }
        };

        topicLv.setAdapter(hotTopicAdapter);


    }

    public void getGanHuoData() {

        String cacheTopic = SpUtil.getInstance().getString(SpKey.HOME_GAN_HUO);
        if (!StringUtil.isEmpty(cacheTopic)) {
            List<GanHuoBean> netList = GsonUtil.fromJsonList(JSONUtil.getArrayData("list", cacheTopic), GanHuoBean.class);
            hotTopicList.clear();
            hotTopicList.addAll(netList);
            hotTopicAdapter.notifyDataSetChanged();
        }


        final NetUtil netUtil = new NetUtil(getActivity(), JsonApi.ARTICLE_LISTS);
        netUtil.setParams("pageSize", "3");
        netUtil.setParams("catId", "275");
        netUtil.setParams("page", "1");

        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {
                List<GanHuoBean> netList = GsonUtil.fromJsonList(JSONUtil.getArrayData("list", data), GanHuoBean.class);

                if (netList != null && netList.size() > 1) {
                    SpUtil.getInstance().savaString(SpKey.HOME_GAN_HUO, data);
                }


                hotTopicList.clear();
                hotTopicList.addAll(netList);
                hotTopicAdapter.notifyDataSetChanged();
            }

        });

    }

    public void getTopNews() {

        // TODO: 2017/8/28  保险头条


        String toutiaoCache = SpUtil.getInstance().getString("toutiao");
        if (!StringUtil.isEmpty(toutiaoCache)) {
            ToutiaoItem toutiaoItem = new Gson().fromJson(toutiaoCache, ToutiaoItem.class);
            List<ToutiaoBean> cacheList = toutiaoItem.data.list;
            toutiaoList.clear();
            toutiaoList.addAll(cacheList);
            initTouTiaoView();
        }

        refreshTopNews();
    }

    private void refreshTopNews() {
        final NetUtil net = new NetUtil(getActivity(), JsonApi.ARTICLE_LISTS);
        net.setParams("page", "1");
        net.setParams("pageSize", "3");
        net.setParams("isTop", "1");

        net.postRequest("", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {

                ToutiaoItem toutiaoItem = new Gson().fromJson(result, ToutiaoItem.class);
                List<ToutiaoBean> netList = toutiaoItem.data.list;
                if (netList != null && netList.size() > 0) {
                    SpUtil.getInstance().savaString("toutiao", result);
                }
                toutiaoList.clear();
                toutiaoList.addAll(netList);

                initTouTiaoView();

            }
        });
    }

    private void initTouTiaoView() {
        touTiaoViews.clear();//记得加这句话，不然可能会产生重影现象
        for (int i = 0; i < toutiaoList.size(); i++) {
            final int position = i;
            //设置滚动的单个布局
            LinearLayout moreView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.item_view_single, null);
            //初始化布局的控件
            TextView tv1 = (TextView) moreView.findViewById(R.id.tv1);

            /**
             * 设置监听
             */
            moreView.findViewById(R.id.rl).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MobclickAgent.onEvent(App.getContext(), "v6_0_0_SY_tixq");

                    openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{toutiaoList.get(position).url});

                }
            });

            //进行对控件赋值
            tv1.setText(toutiaoList.get(i).title);

            //添加到循环滚动数组里面去
            touTiaoViews.add(moreView);
            homeTopNews.setViews(touTiaoViews);
        }
    }

    @Override
    public void onDestroyView() {
        getActivity().unregisterReceiver(receiveBroadCast);
        super.onDestroyView();
        // queenView.destory();
    }

    public String getScore() {
        return "2";
    }

    class ReceiveBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (Constant.ACTION_LOGIN_LOGINOUT.equals(arg1.getAction())) {
                showReportStatus();
                getRecommendData();
            } else if (Constant.ACTION_SUCCESS_LOGIN.equals(arg1.getAction())) {
                ((BaseActivity) getActivity()).getPlanerId();
                showReportStatus();
               getRecommendData();
            } else if (Constant.ACTION_SUCCESS_FAMILY_REPORT_SUCESS.equals(arg1.getAction())) {
                showReportStatus();
            }
        }

    }


    private void initBroadCastReceiver() {
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_LOGIN_LOGINOUT);
        filter.addAction(Constant.ACTION_SUCCESS_LOGIN);
        filter.addAction(Constant.ACTION_SUCCESS_FAMILY_REPORT_SUCESS);
        getActivity().registerReceiver(receiveBroadCast, filter);
    }

    private void getSortData() {
        final NetUtil sortNet = new NetUtil(context, JsonApi.PRODUCT_CONDITION);
        sortNet.postRequest("加载中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                ProductSelectBaseBean bean = new Gson().fromJson(result, ProductSelectBaseBean.class);
                if (bean.data.list != null) {
                    for (int i = 0; i < bean.data.list.size(); i++) {
                        if ( bean.data.list.get(i).name.equals("免费")) {
                            ((MainActivity) getActivity()).productPosition = i;
                            ((MainActivity) getActivity()).setTabSelection(2);
                           break;
                        }

                    }
                }
            }


        });
    }


}
